/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.jdbc.entity;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Factory for building {@link EntityDefinition} instance by specified entity class.
 * Also provide local buffer to avoid duplicacted definition parsing.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-23 11:06
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
abstract public class EntityDefinitionFactory {
    private static final Map<Class, EntityDefinition> buffer = new HashMap<>();

    public static <E extends Serializable> EntityDefinition<E> getEntityDefinition(Class<E> entityClass) {
        Assert.notNull(entityClass, "Entity class must not be null");
        synchronized (buffer) {
            if (buffer.containsKey(entityClass)) {
                //noinspection unchecked
                return buffer.get(entityClass);
            } else {
                EntityDefinition<E> entityDefinition = new DefaultEntityDefinition<E>(entityClass);
                buffer.put(entityClass, entityDefinition);
                return entityDefinition;
            }
        }
    }
}
